﻿using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Service.Permissions;
using DongFangGuoKai.WMSPlatform.Service.Permissions.DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Transactions;

namespace DongFangGuoKai.WMSPlatform.WebApi.Controllers.Permissions
{
    /// <summary>
    /// 菜单管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MenuController : ApiBaseController
    {
        private readonly IPermissionService permissionService;
        private readonly Repository<t_Menu> menurepsot;
        private readonly Repository<t_Action> actionrepost;
        private readonly Repository<t_MenuAction> menuactionrepost;

        public MenuController(IPermissionService permissionService,
            Repository<t_Menu> menurepsot
            ) 
        {
            this.permissionService = permissionService;
            this.menurepsot = menurepsot;
            actionrepost = menurepsot.ChangeRepository<Repository<t_Action>>();
            menuactionrepost = menurepsot.ChangeRepository<Repository<t_MenuAction>>();
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenuList(string? mname = "", int status = 2)
        {
            var melist = menurepsot.GetList();
            if (!string.IsNullOrEmpty(mname))
            {
                melist = melist.Where(x => x.MenuName.Contains(mname)).ToList();
            }
            if (status != 2)
            {
                melist = melist.Where(x => x.Status == status).ToList();
            }
            if (melist.Any())
            {
                melist = melist.OrderBy(x => x.ParentId).ToList();
                var mmlist = melist.FirstOrDefault();
                var data = GetMenuLists(melist.ToList(), mmlist.ParentId.GetValueOrDefault());
                return Success(data);
            }
            var list = GetMenuLists(melist.ToList(), 0);
            return Success(list);
        }
        /// <summary>
        /// 递归显示菜单列表
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static List<MenuDto> GetMenuLists(List<t_Menu> list, int pid)
        {
            try
            {
                return list.Where(x => x.ParentId == pid).Select(x => new MenuDto
                {
                    id = x.Id,
                    ParentId = x.ParentId,
                    MenuUrl = x.MenuUrl,
                    Meta = new MetaDto
                    {
                        MenuName = x.MenuName,
                        MenuIcon = x.MenuIcon,
                    },
                    Status = x.Status,
                    DisplayOrder = x.DisplayOrder,
                    children = GetMenuLists(list, x.Id)
                }).OrderBy(x => x.DisplayOrder).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 左侧穿梭框显示
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetLeftMenuActionList(int mid = 0)
        {
            try
            {
                var missingButtons = actionrepost.GetList().Where(a => !menuactionrepost.GetList()
                .Any(r => r.MenuId == mid && r.ActionId == a.Id)).ToList();
                if (missingButtons != null && missingButtons.Count() > 0)
                {
                    return Success(missingButtons,"查询成功！");
                }
                return Failed("查询失败！");
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 右侧穿梭框显示
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetRightMenuActionList(int mid = 0)
        {
            try
            {
                var missingButtons = actionrepost.GetList().Where(a => menuactionrepost.GetList()
                .Any(r => r.MenuId == mid && r.ActionId == a.Id)).ToList();
               
                if (missingButtons != null && missingButtons.Count() > 0)
                {
                    return Success(missingButtons, "查询成功！");
                }
                return Failed("查询失败！");
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 添加菜单按钮关系
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddMenuAction(TMenuActionDTO m)
        {
            bool IsOK = permissionService.AddMenuAction(m);
            if (IsOK)
            {
                return Success("添加成功");
            }
            return Failed("已经存在该账号!");
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelMenuItem(int mid)
        {
            if (mid <= 0)
            {
                return Failed("Id有误!");
            }
            bool IsOK = permissionService.DelMenuItem(mid);
            if (IsOK)
            {
                return Success("删除成功");
            }
            return Failed("删除失败!");
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddMenuItem(t_Menu m)
        {
            var mobj = menurepsot.GetFirst(x => x.MenuName == m.MenuName);
            if (mobj != null)
            {
                return Failed("添加失败!");
            }
            m.CreateDate = DateTime.Now;
            m.ModifyDate = DateTime.Now;
            if (menurepsot.Insert(m) == null)
            {
                return Failed("添加失败!");
            }
            return Success("添加成功");
        }

        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdMenuItem(t_Menu m)
        {
            if (m.Id <= 0)
            {
                return Failed("Id有误！");
            }

            m.ModifyDate = DateTime.Now;
            if (!menurepsot.Update(m))
            {
                return Failed("修改失败!");
            }
            return Success("修改成功");
        }

        /// <summary>
        /// 分配权限列表显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenuActionList(int rid)
        {
            if (rid <= 0)
            {
                return Failed("Id有误!");
            }
            var list = permissionService.GetMenuActionList(rid);
            if (list != null)
            {
                return Success("查询成功!");
            }
            return Failed("查询失败");
        }

        /// <summary>
        /// 分配权限
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddRoleMenuAction(CRoleMenuAction m)
        {
            if (m.Rid <= 0)
            {
                return Failed("添加失败！");
            }
            var isOk = permissionService.AddRoleMenuAction(m);
            if (isOk)
            {
                return Success("添加成功!");
            }
            return Failed("添加失败！");
        }

        /// <summary>
        /// 根据用户id查询该用户的所有权限
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public IActionResult GetMenuitemAction(int uid)
        {
            if (uid <= 0)
            {
                return Failed("Id有误!");
            }
            var obj = permissionService.GetMenuitemAction(uid);
            if (obj != null)
            {
                return Success(obj,"获取成功!");
            }
            return Failed("获取失败");
        }

        /// <summary>
        /// 根据ID获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenuItem(int id)
        {
            if (id <= 0)
            {
                return Failed("Id有误");
            }
            var obj = menurepsot.GetFirst(m => m.Id == id);
            if (obj == null)
            {
                return Failed("获取失败");
            }
            return Success(obj, "获取成功");
        }
    }
}
